package com.dong.config;

import com.dong.pojo.User;
import com.dong.service.UserService;
import com.dong.service.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/*
自定义的UserRealm
用来认证，授权，拦截等
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserServiceImpl userService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权doGetAuthorization");
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证oGetAuthenticationInfo");
        //转换我们传过来的token
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //获取当前的用户
        //连接真实的数据库
        User user = userService.queryUserByName(userToken.getUsername());
        System.out.println(user.getName());
        if (user ==null){
            return null;//抛出异常 ：UnknownAccountException
        }
        //可以加密 MD5
        //密码认证,shiro做
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
        // principals：身份，即主体的标识属性，如用户名、邮箱等，确保唯一即可。
        // credentials：证明/凭证，即只有主体知道的安全值，如密码/数字证书等。

    }
}
